package com.da.javatest.thread.juc.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chenlida
 * @date 2020/7/11 15:12
 *
 * Condition.await()方法和Object.wait()方法类似，当使用Condition.await()方法时，
 * 需要先获取Condition对象关联的ReentrantLock的锁，在Condition.await()方法被调用时，
 * 当前线程会释放这个锁，并且当前线程会进行等待（处于阻塞状态）。在signal()方法被调用后，
 * 系统会从Condition对象的等待队列中唤醒一个线程，一旦线程被唤醒，被唤醒的线程会尝试重新获取锁，
 * 一旦获取成功，就可以继续执行了。因此，在signal被调用后，一般需要释放相关的锁，让给其他被唤醒的线程，让他可以继续执行。
 */
public class Condition1 {
    private static Lock lock = new ReentrantLock();
    private static Condition condition = lock.newCondition();

    public static class T1 extends Thread {
        @Override
        public void run() {
            System.out.println(this.getName() + "准备获取锁");
            lock.lock();
            try {
                System.out.println(this.getName() + "获取到锁");
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(this.getName() + "释放锁");
        }
    }

    public static class T2 extends Thread {
        @Override
        public void run() {
            System.out.println(this.getName() + "准备获取锁");
            lock.lock();
            try {
                System.out.println(this.getName() + "获取到锁");
                condition.signal();
                System.out.println(this.getName() + "signal");
                TimeUnit.SECONDS.sleep(2);
                System.out.println(this.getName() + "准备释放锁");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            System.out.println(this.getName() + "释放锁");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        T1 t1 = new T1();
        t1.setName("t1");
        t1.start();
        TimeUnit.SECONDS.sleep(3);
        T2 t2 = new T2();
        t2.setName("t2");
        t2.start();
    }
}
